package com.summer.data.rs.map;

import com.summer.data.dialect.Dialect;
import com.summer.data.logging.Logger;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;

/**
 * @author 345480567@qq.com
 */
public class ResultSetMapLogFun<T> extends AbstractResultSetMapFun<T> {

    AbstractResultSetMapFun<T> target;

    private ResultSetMetaData metaData = null;

    public ResultSetMapLogFun(AbstractResultSetMapFun<T> target) {
        this.target = target;
    }

    @Override
    public T map(ResultSet resultSet, Dialect dialect) throws SQLException {
        logSql(resultSet);
        return target.map(resultSet, dialect);
    }

    private void logSql(ResultSet resultSet) throws SQLException {
        if (Logger.isLogSql()) {
            if (metaData == null) {
                metaData = resultSet.getMetaData();

                int columnCount = metaData.getColumnCount();
                Logger.log("<== ");
                for (int i=1; i<=columnCount; i++) {
                    Logger.log("%s \t", metaData.getColumnName(i));
                }
                Logger.log("\r\n");
            }
            int columnCount = metaData.getColumnCount();
            Logger.log("<== ");
            for (int i=1; i<=columnCount; i++) {
                int columnType = metaData.getColumnType(i);
                if (columnType == Types.BLOB) {
                    Logger.log("%s \t", "(BLOB)");
                } else if (columnType == Types.CLOB) {
                    Logger.log("%s \t", "(CLOB)");
                } else if (columnType == Types.LONGVARCHAR) {
                    Object object = resultSet.getObject(i);
                    if (object != null) {
                        int length = object.toString().length();
                        Logger.log("%s(%d) \t", "LONGVARCHAR", length);
                    } else {
                        Logger.log("%s \t", "LONGVARCHAR(null)");
                    }
                } else {
                    Logger.log("%s \t", resultSet.getObject(i));
                }
//                Types.LONGVARCHAR
            }
            Logger.log("\r\n");
        }
    }

}
